package io.g740.util;

import io.g740.dto.Column;
import io.g740.handler.CalculatorContext;
import io.g740.handler.DataMigrationHandler;
import io.g740.handler.FullQuantityNotReservedDataMigrationHandler;
import io.g740.service.MigrationConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * sql工具
 *
 * @author YunKaiLuo
 * @date 2024/10/19
 */
public class ServiceUtil {
    private static final Logger log = LoggerFactory.getLogger(ServiceUtil.class);

    private ServiceUtil() {
    }

    public static void validateColumn(Map<String, Column> columnsInfo, Set<String> columnNames) {
        Set<String> columnNamesInDB = columnsInfo.keySet();
        for (String columnName : columnNames) {
            if (!columnNamesInDB.contains(columnName.toLowerCase())) {
                throw new IllegalArgumentException("数据库中不存在该字段：" + columnName);
            }
        }
    }

    public static void changeOptions(List<String> tableOptionsStrings, String key, String value) {
        boolean match = false;
        boolean equal = false;
        for (int i = 0; i < tableOptionsStrings.size(); i++) {
            String option = tableOptionsStrings.get(i);
            if (option.equals(key)) {
                match = true;
            }
            if (match && option.equals("=")) {
                equal = true;
            }
            if (match && equal) {
                tableOptionsStrings.set(++i, value);
                match = false;
                equal = false;
            }
        }
    }

    public static void migrateData(MigrationConfig migrationConfig, Connection sourceConn, Connection targetConn) throws SQLException {
        CalculatorContext dataMigrationHandler = new CalculatorContext(migrationConfig);
        dataMigrationHandler.migrate(migrationConfig, sourceConn, targetConn);
    }
}
